<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\common\model\Course as CourseModel;
use app\common\model\CourseQuestion;
use think\Db;
use app\common\model\Exam as ExamModel;

class Course extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function index()
    {
        // 获取搜索关键词
        $keyword = $this->request->get('keyword', '');
        
        // 获取热门课程数据（使用LEFT JOIN优化查询）
        $courseModel = new CourseModel();
        $courseList = $courseModel->alias('c')
                                 ->join('think_exam e', 'c.exam_id = e.id')
                                 ->where('c.status', 1)
                                 ->where('c.on_sale', 1)
                                 ->field('c.*, e.name as exam_name')
                                 ->order('c.sale_num desc, c.sort desc')
                                 ->limit(6)
                                 ->select();
        
        // 转换数据格式以适配视图
        $hotCourses = [];
        foreach ($courseList as $course) {
            $hotCourses[] = [
                 'id' => $course['id'],
                 'title' => $course['name'],
                 'code' => $course['code'],
                 'description' => $course['desc'] ?: '暂无课程介绍',
                 'question_count' => rand(500, 2000), // 题目数量暂时随机生成
                 'study_count' => $course['sale_num'],
                 'difficulty' => $this->getDifficultyByPrice($course['price']),
                 'category' => $course['exam_name'] ?: '其他',
                 'price' => $course['price']
             ];
        }
        
        // 搜索结果
        $searchResults = [];
        if (!empty($keyword)) {
            $searchList = $courseModel->alias('c')
                                    ->join('think_exam e', 'c.exam_id = e.id')
                                    ->where('c.status', 1)
                                    ->where('c.on_sale', 1)
                                    ->where('c.name|c.desc', 'like', '%' . $keyword . '%')
                                    ->field('c.*, e.name as exam_name')
                                    ->order('c.sale_num desc')
                                    ->limit(12)
                                    ->select();
            
            foreach ($searchList as $course) {
                $searchResults[] = [
                     'id' => $course['id'],
                     'title' => $course['name'],
                     'code' => $course['code'],
                     'description' => $course['desc'] ?: '暂无课程介绍',
                     'question_count' => rand(500, 2000),
                     'study_count' => $course['sale_num'],
                     'difficulty' => $this->getDifficultyByPrice($course['price']),
                     'category' => $course['exam_name'] ?: '其他',
                     'price' => $course['price']
                 ];
            }
        }
        
        // 获取随机题目动态数据
        $questionDynamics = CourseQuestion::getRandomQuestionDynamics(10);
        
        // 格式化题目动态数据
        $formattedDynamics = [];
        foreach ($questionDynamics as $item) {
            $timeAgo = $this->timeAgo($item['a_time']);
            $formattedDynamics[] = [
                'id' => $item['id'],
                'user_name' => '系统管理员',
                'question_title' => $item['question_name'],
                'course_name' => $item['course_name'],
                'upload_time' => $timeAgo,
                'detail_url' => url('question/detail', ['id' => $item['id']])
            ];
        }
        $questionDynamics = $formattedDynamics;
        
        $this->view->assign([
             'keyword' => $keyword,
             'hotCourses' => $hotCourses,
             'searchResults' => $searchResults,
             'questionDynamics' => $questionDynamics,
             'hasSearch' => !empty($keyword)
         ]);
         
         return $this->view->fetch();
    }
    
    /**
     * 根据价格判断难度
     */
    private function getDifficultyByPrice($price)
    {
        if ($price <= 50) {
            return '简单';
        } elseif ($price <= 200) {
            return '中等';
        } else {
            return '困难';
        }
    }
    
    /**
     * 格式化时间为相对时间
     * @param int $timestamp
     * @return string
     */
    private function timeAgo($timestamp)
    {
        $now = time();
        $diff = $now - $timestamp;
        
        if ($diff < 60) {
            return '刚刚';
        } elseif ($diff < 3600) {
            return floor($diff / 60) . '分钟前';
        } elseif ($diff < 86400) {
            return floor($diff / 3600) . '小时前';
        } elseif ($diff < 2592000) {
            return floor($diff / 86400) . '天前';
        } else {
            return date('Y-m-d', $timestamp);
        }
    }

}